<?php

namespace App\Http\Middleware\OpenShop;

use App\Library\Rms\RmsUserApi;
use App\Service\OpenShop\User\RmsUserService;
use Closure;
use Illuminate\Http\Request;

class FeishuWebAuth
{
    public static $userId = 0;

    /**
     * 验证飞书PC网页是否登录
     * @param Request $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (config('app.env') == 'dev') {
            $userInfo = (object)(new RmsUserApi())->getUserInfoByMobiles(['13917836275'])['data'][0] ?? [];

            $userInfo          = RmsUserService::getRmsAuthUserInfo($userInfo->id);
            $request->userInfo = (object)$userInfo['data'];
            self::$userId = $request->userInfo->id;

            $request->setUserResolver(function () use ($userInfo) {
                return (object)$userInfo["data"];
            });
            return $next($request);
        }

        $userInfo = RmsUserService::getAuthUserInfo($request->headers->all());
        $id       = self::$userId = $userInfo['data']['id'] ?? 0;

        if ($id) {
            $request->setUserResolver(function () use ($userInfo) {
                return (object)$userInfo["data"];
            });

            $request->userInfo = (object)$userInfo['data'];
            return $next($request);
        }
        return response()->json(['code' => 401, 'msg' => '尚未登录']);
    }
}
